<!DOCTYPE html>
<html lang="zh-cn"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/main.css" rel="stylesheet">

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico" />

    <title>Go程序的for结构 | wiseAI的小站</title>
</head><body><div class="container-fluid">
    <nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">
                <img src="/img/favicon.ico" alt="" width="30" height="24" class="d-inline-block align-text-top">
                wiseAI的小站
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/articles/">文章</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/categories/">分类</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/tags/">关键字</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/post/golang/">golang编程</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/about/">关于</a>
                    </li>
                    
                </ul>
                <form class="d-flex">
                    <input id="search-query" class="form-control me-2" type="search" placeholder="Search for anything..." aria-label="Search">
                </form>
            </div>
        </div>
    </nav>
</div>




<div id="content">
<div class="container article">
	<h1>Go程序的for结构</h1>
	<div class="post-meta">
		<div>
			
			
			By wiseai | 2022-07-11 | 7 minutes
		</div>
		<div class="tags">
			
			<a class="btn btn-light links btn-sm" href="/tags/%E7%BC%96%E7%A8%8B/">编程</a>
			
		</div>
	</div>
	<div>
		<div class="article-post">
			<h1 id="54-for-结构">5.4 for 结构</h1>
<p>如果想要重复执行某些语句，Go 语言中您只有 <code>for</code> 结构可以使用。不要小看它，这个 <code>for</code> 结构比其它语言中的更为灵活。</p>
<p><strong>注意事项</strong> 其它许多语言中也没有发现和 do-while 完全对等的 <code>for</code> 结构，可能是因为这种需求并不是那么强烈。</p>
<h2 id="541-基于计数器的迭代">5.4.1 基于计数器的迭代</h2>
<p>文件 for1.go 中演示了最简单的基于计数器的迭代，基本形式为：</p>
<pre><code>for 初始化语句; 条件语句; 修饰语句 {}
</code></pre>
<p>示例 5.6 <a href="examples/chapter_5/for1.go">for1.go</a>：</p>
<pre tabindex="0"><code>package main

import &#34;fmt&#34;

func main() {
	for i := 0; i &lt; 5; i++ {
		fmt.Printf(&#34;This is the %d iteration\n&#34;, i)
	}
}
</code></pre><p>输出：</p>
<pre><code>This is the 0 iteration
This is the 1 iteration
This is the 2 iteration
This is the 3 iteration
This is the 4 iteration
</code></pre>
<p>由花括号括起来的代码块会被重复执行已知次数，该次数是根据计数器（此例为 <code>i</code>）决定的。循环开始前，会执行且仅会执行一次初始化语句 <code>i := 0;</code>；这比在循环之前声明更为简短。紧接着的是条件语句 <code>i &lt; 5;</code>，在每次循环开始前都会进行判断，一旦判断结果为 <code>false</code>，则退出循环体。最后一部分为修饰语句 <code>i++</code>，一般用于增加或减少计数器。</p>
<p>这三部分组成的循环的头部，它们之间使用分号 <code>;</code> 相隔，但并不需要括号 <code>()</code> 将它们括起来。例如：<code>for (i = 0; i &lt; 10; i++) { }</code>，这是无效的代码！</p>
<p>同样的，左花括号 <code>{</code> 必须和 for 语句在同一行，计数器的生命周期在遇到右花括号 <code>}</code> 时便终止。一般习惯使用 i、j、z 或 ix 等较短的名称命名计数器。</p>
<p>特别注意，永远不要在循环体内修改计数器，这在任何语言中都是非常差的实践！</p>
<p>您还可以在循环中同时使用多个计数器：</p>
<pre tabindex="0"><code>for i, j := 0, N; i &lt; j; i, j = i+1, j-1 {}
</code></pre><p>这得益于 Go 语言具有的平行赋值的特性（可以查看<a href="07.0.md">第 7 章</a> <a href="./examples/chapter_7/string_reverse.go">string_reverse.go</a> 中反转数组的示例）。</p>
<p>您可以将两个 for 循环嵌套起来：</p>
<pre tabindex="0"><code>for i:=0; i&lt;5; i++ {
	for j:=0; j&lt;10; j++ {
		println(j)
	}
}
</code></pre><p>如果您使用 for 循环迭代一个 Unicode 编码的字符串，会发生什么？</p>
<p>示例 5.7 <a href="examples/chapter_5/for_string.go">for_string.go</a>：</p>
<pre tabindex="0"><code>package main

import &#34;fmt&#34;

func main() {
	str := &#34;Go is a beautiful language!&#34;
	fmt.Printf(&#34;The length of str is: %d\n&#34;, len(str))
	for ix :=0; ix &lt; len(str); ix++ {
		fmt.Printf(&#34;Character on position %d is: %c \n&#34;, ix, str[ix])
	}
	str2 := &#34;日本語&#34;
	fmt.Printf(&#34;The length of str2 is: %d\n&#34;, len(str2))
	for ix :=0; ix &lt; len(str2); ix++ {
		fmt.Printf(&#34;Character on position %d is: %c \n&#34;, ix, str2[ix])
	}
}
</code></pre><p>输出：</p>
<pre><code>The length of str is: 27
Character on position 0 is: G 
Character on position 1 is: o 
Character on position 2 is:   
Character on position 3 is: i 
Character on position 4 is: s 
Character on position 5 is:   
Character on position 6 is: a 
Character on position 7 is:   
Character on position 8 is: b 
Character on position 9 is: e 
Character on position 10 is: a 
Character on position 11 is: u 
Character on position 12 is: t 
Character on position 13 is: i 
Character on position 14 is: f 
Character on position 15 is: u 
Character on position 16 is: l 
Character on position 17 is:   
Character on position 18 is: l 
Character on position 19 is: a 
Character on position 20 is: n 
Character on position 21 is: g 
Character on position 22 is: u 
Character on position 23 is: a 
Character on position 24 is: g 
Character on position 25 is: e 
Character on position 26 is: ! 
The length of str2 is: 9
Character on position 0 is: æ 
Character on position 1 is:  
Character on position 2 is: ¥ 
Character on position 3 is: æ 
Character on position 4 is:  
Character on position 5 is: ¬ 
Character on position 6 is: è 
Character on position 7 is: ª 
Character on position 8 is:  
</code></pre>
<p>如果我们打印 <code>str</code> 和 <code>str2</code> 的长度，会分别得到 <code>27</code> 和 <code>9</code>。</p>
<p>由此我们可以发现，ASCII 编码的字符占用 1 个字节，既每个索引都指向不同的字符，而非 ASCII 编码的字符（占有 2 到 4 个字节）不能单纯地使用索引来判断是否为同一个字符。我们会在<a href="05.4.md">第 5.4.4 节</a> 解决这个问题。</p>
<h3 id="练习题">练习题</h3>
<p><strong>练习 5.4</strong> <a href="exercises/chapter_5/for_loop.go">for_loop.go</a></p>
<ol>
<li>使用 <code>for</code> 结构创建一个简单的循环。要求循环 15 次然后使用 <code>fmt</code> 包来打印计数器的值。</li>
<li>使用 <code>goto</code> 语句重写循环，要求不能使用 <code>for</code> 关键字。</li>
</ol>
<p><strong>练习 5.5</strong> <a href="exercises/chapter_5/for_character.go">for_character.go</a></p>
<p>创建一个程序，要求能够打印类似下面的结果（尾行达 25 个字符为止）：</p>
<pre><code>G
GG
GGG
GGGG
GGGGG
GGGGGG
</code></pre>
<ol>
<li>使用 2 层嵌套 for 循环。</li>
<li>仅用 1 层 for 循环以及字符串连接。</li>
</ol>
<p><strong>练习 5.6</strong> <a href="exercises/chapter_5/bitwise_complement.go">bitwise_complement.go</a></p>
<p>使用按位补码从 0 到 10，使用位表达式 <code>%b</code> 来格式化输出。</p>
<p><strong>练习 5.7</strong> Fizz-Buzz 问题：<a href="exercises/chapter_5/fizzbuzz.go">fizzbuzz.go</a></p>
<p>写一个从 1 打印到 100 的程序，但是每当遇到 3 的倍数时，不打印相应的数字，但打印一次 &ldquo;Fizz&rdquo;。遇到 5 的倍数时，打印 <code>Buzz</code> 而不是相应的数字。对于同时为 3 和 5 的倍数的数，打印 <code>FizzBuzz</code>（提示：使用 switch 语句）。</p>
<p><strong>练习 5.8</strong> <a href="exercises/chapter_5/rectangle_stars.go">rectangle_stars.go</a></p>
<p>使用 <code>*</code> 符号打印宽为 20，高为 10 的矩形。</p>
<h2 id="542-基于条件判断的迭代">5.4.2 基于条件判断的迭代</h2>
<p>for 结构的第二种形式是没有头部的条件判断迭代（类似其它语言中的 while 循环），基本形式为：<code>for 条件语句 {}</code>。</p>
<p>您也可以认为这是没有初始化语句和修饰语句的 for 结构，因此 <code>;;</code> 便是多余的了。</p>
<p>Listing 5.8 <a href="examples/chapter_5/for2.go">for2.go</a>：</p>
<pre tabindex="0"><code>package main

import &#34;fmt&#34;

func main() {
	var i int = 5

	for i &gt;= 0 {
		i = i - 1
		fmt.Printf(&#34;The variable i is now: %d\n&#34;, i)
	}
}
</code></pre><p>输出：</p>
<pre><code>The variable i is now: 4
The variable i is now: 3
The variable i is now: 2
The variable i is now: 1
The variable i is now: 0
The variable i is now: -1
</code></pre>
<h2 id="543-无限循环">5.4.3 无限循环</h2>
<p>条件语句是可以被省略的，如 <code>i:=0; ; i++</code> 或 <code>for { }</code> 或 <code>for ;; { }</code>（<code>;;</code> 会在使用 gofmt 时被移除）：这些循环的本质就是无限循环。最后一个形式也可以被改写为 <code>for true { }</code>，但一般情况下都会直接写 <code>for { }</code>。</p>
<p>如果 for 循环的头部没有条件语句，那么就会认为条件永远为 true，因此循环体内必须有相关的条件判断以确保会在某个时刻退出循环。</p>
<p>想要直接退出循环体，可以使用 break 语句（第 5.5 节）或 return 语句直接返回（第 6.1 节）。</p>
<p>但这两者之间有所区别，break 只是退出当前的循环体，而 return 语句提前对函数进行返回，不会执行后续的代码。</p>
<p>无限循环的经典应用是服务器，用于不断等待和接受新的请求。</p>
<pre tabindex="0"><code>for t, err = p.Token(); err == nil; t, err = p.Token() {
	...
}
</code></pre><h2 id="544-for-range-结构">5.4.4 for-range 结构</h2>
<p>这是 Go 特有的一种的迭代结构，您会发现它在许多情况下都非常有用。它可以迭代任何一个集合（包括数组和 <code>map</code>，详见第 <a href="07.0.md">7</a> 和 <a href="08.0.md">8</a> 章）。语法上很类似其它语言中的 foreach 语句，但您依旧可以获得每次迭代所对应的索引。一般形式为：<code>for ix, val := range coll { }</code>。</p>
<p>要注意的是，<code>val</code> 始终为集合中对应索引的值拷贝，因此它一般只具有只读性质，对它所做的任何修改都不会影响到集合中原有的值（<strong>译者注：如果 <code>val</code> 为指针，则会产生指针的拷贝，依旧可以修改集合中的原值</strong>）。一个字符串是 Unicode 编码的字符（或称之为 <code>rune</code>）集合，因此您也可以用它迭代字符串：</p>
<pre tabindex="0"><code>for pos, char := range str {
...
}
</code></pre><p>每个 <code>rune</code> 字符和索引在 for-range 循环中是一一对应的。它能够自动根据 UTF-8 规则识别 Unicode 编码的字符。</p>
<p>示例 5.9 <a href="examples/chapter_5/range_string.go">range_string.go</a>：</p>
<pre tabindex="0"><code>package main

import &#34;fmt&#34;

func main() {
	str := &#34;Go is a beautiful language!&#34;
	fmt.Printf(&#34;The length of str is: %d\n&#34;, len(str))
	for pos, char := range str {
		fmt.Printf(&#34;Character on position %d is: %c \n&#34;, pos, char)
	}
	fmt.Println()
	str2 := &#34;Chinese: 日本語&#34;
	fmt.Printf(&#34;The length of str2 is: %d\n&#34;, len(str2))
	for pos, char := range str2 {
    	fmt.Printf(&#34;character %c starts at byte position %d\n&#34;, char, pos)
	}
	fmt.Println()
	fmt.Println(&#34;index int(rune) rune    char bytes&#34;)
	for index, rune := range str2 {
    	fmt.Printf(&#34;%-2d      %d      %U &#39;%c&#39; % X\n&#34;, index, rune, rune, rune, []byte(string(rune)))
	}
}
</code></pre><p>输出：</p>
<pre tabindex="0"><code>The length of str is: 27
Character on position 0 is: G 
Character on position 1 is: o 
Character on position 2 is:   
Character on position 3 is: i 
Character on position 4 is: s 
Character on position 5 is:   
Character on position 6 is: a 
Character on position 7 is:   
Character on position 8 is: b 
Character on position 9 is: e 
Character on position 10 is: a 
Character on position 11 is: u 
Character on position 12 is: t 
Character on position 13 is: i 
Character on position 14 is: f 
Character on position 15 is: u 
Character on position 16 is: l 
Character on position 17 is:   
Character on position 18 is: l 
Character on position 19 is: a 
Character on position 20 is: n 
Character on position 21 is: g 
Character on position 22 is: u 
Character on position 23 is: a 
Character on position 24 is: g 
Character on position 25 is: e 
Character on position 26 is: ! 

The length of str2 is: 18
character C starts at byte position 0
character h starts at byte position 1
character i starts at byte position 2
character n starts at byte position 3
character e starts at byte position 4
character s starts at byte position 5
character e starts at byte position 6
character : starts at byte position 7
character   starts at byte position 8
character 日 starts at byte position 9
character 本 starts at byte position 12
character 語 starts at byte position 15

index int(rune) rune    char bytes
0       67      U+0043 &#39;C&#39; 43
1       104      U+0068 &#39;h&#39; 68
2       105      U+0069 &#39;i&#39; 69
3       110      U+006E &#39;n&#39; 6E
4       101      U+0065 &#39;e&#39; 65
5       115      U+0073 &#39;s&#39; 73
6       101      U+0065 &#39;e&#39; 65
7       58      U+003A &#39;:&#39; 3A
8       32      U+0020 &#39; &#39; 20
9       26085      U+65E5 &#39;日&#39; E6 97 A5
12      26412      U+672C &#39;本&#39; E6 9C AC
15      35486      U+8A9E &#39;語&#39; E8 AA 9E
</code></pre><p>请将输出结果和 Listing 5.7（<a href="examples/chapter_5/for_string.go">for_string.go</a>）进行对比。</p>
<p>我们可以看到，常用英文字符使用 1 个字节表示，而汉字（<strong>译者注：严格来说，“Chinese: 日本語”的 Chinese 应该是 Japanese</strong>）使用 3 个字符表示。</p>
<p><strong>练习 5.9</strong> 以下程序的输出结果是什么？</p>
<pre tabindex="0"><code>for i := 0; i &lt; 5; i++ {
	var v int
	fmt.Printf(&#34;%d &#34;, v)
	v = 5
}
</code></pre><p><strong>问题 5.2：</strong> 请描述以下 for 循环的输出结果：</p>
<ol>
<li></li>
</ol>
<pre tabindex="0"><code>for i := 0; ; i++ {
	fmt.Println(&#34;Value of i is now:&#34;, i)
}
</code></pre><ol start="2">
<li></li>
</ol>
<pre tabindex="0"><code>for i := 0; i &lt; 3; {
	fmt.Println(&#34;Value of i:&#34;, i)
}
</code></pre><ol start="3">
<li></li>
</ol>
<pre tabindex="0"><code>s := &#34;&#34;
for ; s != &#34;aaaaa&#34;; {
	fmt.Println(&#34;Value of s:&#34;, s)
	s = s + &#34;a&#34;
}
</code></pre><ol start="4">
<li></li>
</ol>
<pre tabindex="0"><code>for i, j, s := 0, 5, &#34;a&#34;; i &lt; 3 &amp;&amp; j &lt; 100 &amp;&amp; s != &#34;aaaaa&#34;; i, j,
	s = i+1, j+1, s + &#34;a&#34; {
	fmt.Println(&#34;Value of i, j, s:&#34;, i, j, s)
}
</code></pre>
		</div>
	</div>
</div>


<div class="container">
    
    <div class="row">
        
        <div class="col-5">
            <a class="page-link link-dark text-end dh" href="/post/golang/2022.07.10-switch%E7%BB%93%E6%9E%84/">
                <h5>前一篇</h5><br>
                Go程序的switch结构
            </a>            
        </div>
        
        <div class="col-2">
        </div>
        
        <div class="col-5">
            <a class="page-link link-dark text-start dh" href="/post/golang/2022.07.12-break%E4%B8%8Econtinue/">
                <h5>后一篇</h5><br>
                Go程序的Break与continue
            </a>            
        </div>
        
    </div>
    
</div>

        </div><br><br>
<footer class="container">
    <h2>友情链接</h2>
    <hr>
    <nav class="nav nav-pills flex-column flex-sm-row">
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/gnzg/index.html" target="_blank">孤鸟之歌</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/mm/index.html" target="_blank">生成随机字符</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/md/index.html" target="_blank">MarkDown</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/" target="_blank">Gitee</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://github.com/" target="_blank">Github</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyun.com/" target="_blank">阿里云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cloud.tencent.com/" target="_blank">腾讯云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.oschina.net/" target="_blank">OSCHINA开源中国</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/wiseai/the-way-to-go_ZH_CN/blob/master/eBook/directory.md" target="_blank">the way to go</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://topgoer.com/" target="_blank">golang文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://goframe.org/display/gf" target="_blank">GoFrame</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyundrive.com/" target="_blank">阿里云盘</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cn.vuejs.org/" target="_blank">vue3文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://element-plus.gitee.io/zh-CN/" target="_blank">element-plus文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.runoob.com/vue3/vue3-tutorial.html" target="_blank">vue3菜鸟教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://v5.bootcss.com/" target="_blank">bootstrap v5 中文文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.bootstrap.cn/" target="_blank">bootstrap文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://caddy2.dengxiaolong.com/docs/" target="_blank">caddy中文教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.58pic.com/" target="_blank">千图</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://ifonts.com/" target="_blank">iFonts</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://marketing.qiniu.com/" target="_blank">七牛云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.ixigua.com/" target="_blank">西瓜视频</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/yugang/index.html" target="_blank">鱼缸计算</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://justcc.mengkang.net/#/" target="_blank">C语言JustCC</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/pptist/" target="_blank">PPTist</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="/index.xml" target="_blank">RSS</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.kancloud.cn/idcpj/python/418553" target="_blank">参考资料</a>
        
    </nav>

    <div class="copyright text-center">
      <span class="power-by">
        Powered by <a class="links" href="https://gohugo.io" target="_blank">Hugo</a>
    </span>
    <span>|</span>
    <span>
        Theme - <a class="links" href="https://github.com/wiseai-go/blog-hugo" target="_blank">WiseAI</a>
    </span>
    <br>
    <span class="copyright-year">
        &copy;
        
        2017 -
        2023<span>
            陇ICP备15000157号
            
        </span></span>

</div>
</footer>
<script src="/js/bootstrap.bundle.min.js"></script>


</body>
</html>
